<?php

class ServiceUserIdentity extends UserIdentity {

    const ERROR_NOT_AUTHENTICATED = 3;

    protected $service;

    public function __construct($service) {
        $this->service = $service;
    }

    public function authenticate() {
        if($this->service->isAuthenticated) {
            $name = $this->service->getAttribute('name');
            $email = array($this->service->getServiceName(), $this->service->getId());
            $user = User::model()->find("service_name = ? AND identity = ?", $email);
            if(!$user) {
                $user = new User();
                $user->username = $name;
                $ne = substr(md5($this->service->getServiceName() . $this->service->getId()), 0, 12);
                $user->email = $ne . "@example.com";
                $user->password = User::encrypt(substr(md5(time()), 0, 8));
                $user->status = User::STATUS_ACTIVE;
                $user->role = User::ROLE_USER;
                $user->service_name = $this->service->getServiceName();
                $user->identity = $this->service->getId();
                $user->t_create = time();
                $user->save(false);
                $user->refresh();
            }
            if($user) {
                $this->id = $user->id;
                $this->username = $user->username;
                $this->errorCode = self::ERROR_NONE;
            }
        } else {
            $this->errorCode = self::ERROR_NOT_AUTHENTICATED;
        }
        return !$this->errorCode;
    }
}
